package io.github.shang11925.sbvuewelearn.service.impl;

import io.github.shang11925.sbvuewelearn.dao.ChaptersRepository;
import io.github.shang11925.sbvuewelearn.dto.ChaptersDTO;
import io.github.shang11925.sbvuewelearn.entity.Chapters;
import io.github.shang11925.sbvuewelearn.mapper.ChapterMapper;
import io.github.shang11925.sbvuewelearn.service.ChaptersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ChaptersServiceImpl implements ChaptersService {
    @Autowired
    ChaptersRepository chaptersRepository;

    @Autowired
    ChapterMapper chapterMapper;
    @Override
    public List<Chapters> findAll() {
        return chaptersRepository.findAll();
    }

    @Override
    public List<Chapters> findByCourseId(Long courseId) {
        return chaptersRepository.findByCourseId(courseId);
    }

    @Override
    public void add(ChaptersDTO chaptersDTO) {
        Chapters chapters = new Chapters();
        chapters.setTitle(chaptersDTO.getTitle());
        chapters.setCourseId(chaptersDTO.getCourse_id());

        chaptersRepository.save(chapters);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        chapterMapper.deletevideo_resourcesByChapter(id);
        chapterMapper.deletetext_contentsByChapter(id);
        chapterMapper.deletetext_imagesByChapter(id);
        chapterMapper.deletevideo_attachmentsByChapter(id);
        chapterMapper.deleteAllSection(id);
        chapterMapper.deleteAllChapter(id);
    }

    @Override
    @Transactional
    public void update(Long chapterId, ChaptersDTO chaptersDTO) {
        Chapters chapters = chaptersRepository.findById(chapterId)
                .orElseThrow(() -> new RuntimeException("课程不存在"));

        chapters.setTitle(chaptersDTO.getTitle());
        chaptersRepository.save(chapters);
    }

    @Override
    public long count() {
        return chapterMapper.count();
    }
}
